package com.xuecheng.ucenter.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xuecheng.ucenter.mapper.XcMenuMapper;
import com.xuecheng.ucenter.mapper.XcUserMapper;
import com.xuecheng.ucenter.model.dto.AuthParamsDto;
import com.xuecheng.ucenter.model.dto.XcUserExt;
import com.xuecheng.ucenter.model.po.XcMenu;
import com.xuecheng.ucenter.model.po.XcUser;
import com.xuecheng.ucenter.service.AuthService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;


@Slf4j
@Component//todo 重写springSecurity框架中的UserDetailsService
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    XcMenuMapper xcMenuMapper;
    @Autowired
    ApplicationContext applicationContext;

//  todo 输入账号密码生成令牌,登陆成功后会存在cookie中,jwt-相应的值
    @Override//UserDetails接口  String s 是输入的username
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
//        账号
        AuthParamsDto authParamsDto = null;
        try {
            authParamsDto = JSON.parseObject(s, AuthParamsDto.class);
        } catch (Exception e) {
            throw new RuntimeException("请求参数不符合要求");
        }

//        todo 策略模式
        String authType = authParamsDto.getAuthType();//认证类别
//        根据认证类型从spring容器中取出指定的 bean
        String beanName = authType + "_authservice";
        AuthService authService = applicationContext.getBean(beanName, AuthService.class);
//        调度统一的execute实现方法完成
        XcUserExt xcUserExt = authService.execute(authParamsDto);
        UserDetails userPrincipal = getUserPrincipal(xcUserExt);
        return userPrincipal;
    }

    /**
     * @description 查询用户信息
     * @param xcUser  用户id，主键
     * @return com.xuecheng.ucenter.model.po.XcUser 用户信息
     */
    public UserDetails getUserPrincipal(XcUserExt xcUser){
        //      查询到了用户要封装成UserDetails对象
        String password = xcUser.getPassword();
//        给予权限
        String[] authorities = {"test"};//没有权限也报错
        List<XcMenu> xcMenus = xcMenuMapper.selectPermissionByUserId(xcUser.getId());//获取该用户的权限
        if (xcMenus.size() > 0){
            List<String> permissions = new ArrayList<>();
            xcMenus.forEach(m ->{
                permissions.add(m.getCode());
            });
//   转为数组 当集合有元素时，toArray() 会忽略传入数组的长度（即使是 0），自动创建一个与集合大小匹配的新数组，并将元素复制进去。
//  在 Java 6 之后，传递空数组（new String[0]）和传递指定长度的数组（new String[list.size()]）在性能上没有区别，甚至空数组更简洁
            authorities = permissions.toArray(new String[0]);
        }

//        UserDetails userDetails = User.withUsername(username).password(password).authorities(authorities).build();
//        往jwt令牌存入更多的信息User.withUsername(username)
        xcUser.setPassword(null);//敏感信息
        String jsonString = JSON.toJSONString(xcUser);//把这个对象变成json类型,在jwt令牌中进行携带
        UserDetails userDetails = User.withUsername(jsonString).password(password).authorities(authorities).build();
        return userDetails;
    }
}
